package com.chinda.common.exception;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.chinda.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 异常
 * @author Wang Chinda
 * @date 2020/8/8
 * @see
 * @since 1.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e) {
        log.error("系统异常：", e);
        return R.error();
    }

    @ExceptionHandler(RRException.class)
    public R rrExceptionHandler(RRException e) {
        return R.error(e.getCode(), e.getMsg());
    }

    /**
     * @Valid全局异常处理
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R validExceptionHandler(MethodArgumentNotValidException e) {
        log.error("数据校验异常: ", e);
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> errorMessages = CollUtil.newArrayList();
        Iterator var5 = fieldErrors.iterator();

        while(var5.hasNext()) {
            FieldError error = (FieldError)var5.next();
            errorMessages.add(error.getField() + error.getDefaultMessage());
        }
        return R.error(errorMessages.stream().collect(Collectors.joining(StrUtil.COMMA)));
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public R duplicateKeyExceptionHandler(DuplicateKeyException e){
        log.error(e.getMessage(), e);
        return R.error("数据库中已存在该记录");
    }

    @ExceptionHandler(EmptyResultDataAccessException.class)
    public R emptyResultDataAccessExceptionHandler(EmptyResultDataAccessException e) {
        log.error(e.getMessage(), e);
        return R.error("数据库中不存在该记录");
    }

//    @ExceptionHandler(AuthenticationException.class)
//    public R authorizationExceptionHandler(AuthenticationException e){
//        log.error(e.getMessage(), e);
//        return R.error("没有权限，请联系管理员授权");
//    }
}
